package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.DimMiningFace;
import net.hn.hnms.biz.plan.domain.PlanPriorityWork;
import net.hn.hnms.biz.plan.mapper.PlanPriorityWorkMapper;
import net.hn.hnms.biz.plan.request.PlanPriorityWorkReq;
import net.hn.hnms.biz.plan.service.PlanPriorityWorkService;
import net.hn.hnms.biz.plan.vo.PlanPriorityWorkVo;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@DS("master")
public class PlanPriorityWorkServiceImpl extends BaseService<PlanPriorityWork, PlanPriorityWorkVo> implements PlanPriorityWorkService {


    @Autowired
    private PlanPriorityWorkMapper planPriorityWorkMapper;
    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public ResponsePage<PlanPriorityWorkVo> selectPageList(PlanPriorityWorkReq planMining, PageQuery pageQuery) {
        Page<PlanPriorityWork> page = planPriorityWorkMapper.selectPage(pageQuery.build(), buildQuery(planMining).orderByDesc(PlanPriorityWork::getPriorityPlanCode).orderByDesc(PlanPriorityWork::getCreateTime));
        List<PlanPriorityWorkVo> list = page.getRecords().stream().map(o -> convert(o, PlanPriorityWorkVo.class,o.getPriorityPlanType())).collect(Collectors.toList());
        list.forEach(ii->{
            LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(ii.getCreateUserId()));
            if (Optional.ofNullable(userInfoById).isPresent()) {
                ii.setCreateUserName(userInfoById.getNickname());
            }

        });

        return new ResponsePage<>(list, page.getTotal());
    }

    @Override
    public List<PlanPriorityWorkVo> selectList(PlanPriorityWorkReq planMining) {
        List<PlanPriorityWork> list = planPriorityWorkMapper.selectList(buildQuery(planMining));
        return list.stream().map(o -> convert(o, PlanPriorityWorkVo.class, o.getPriorityPlanType())).collect(Collectors.toList());
    }

    @Override
    public int insert(PlanPriorityWorkReq planMining) {


//        QueryWrapper<PlanPriorityWork> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("priority_plan_code", planMining.getPriorityPlanCode());
//
//        if (planPriorityWorkMapper.selectCount(queryWrapper) > 0) {
//            throw new HuaNengException(Constants.FAIL, "已存在相同的工作面编号");
//        }
//        PlanPriorityWork insertObj = new PlanPriorityWork();
//        BeanUtil.copyProperties(planMining, insertObj);
//        insertObj.setStatus("0");
//
//        return planPriorityWorkMapper.insert(insertObj);
        PlanPriorityWork insertObj = new PlanPriorityWork();
        copyProperties(planMining, insertObj, planMining.getPriorityPlanType());
        //自动生成 计划名称 计划编号
        if(planMining.getPriorityPlanType().equals("3")){
//            insertObj.setRepairPlanName(generatePlanName(planMining.getRepairPlanType(),insertObj.getWeekTimeStart()));
//            insertObj.setDrivagePlanCode(generatePlanCode(planMining.getRepairPlanType(),insertObj.getWeekTimeStart()));
//            insertObj.setPlanStartDate(insertObj.getWeekTimeStart());
//            insertObj.setPlanEndDate(insertObj.getWeekTimeEnd());
        }else{
            insertObj.setPriorityPlanName(generatePlanName(planMining.getPriorityPlanType(),insertObj.getPlanStartDate()));
            insertObj.setPriorityPlanCode(generatePlanCode(planMining.getPriorityPlanType(),insertObj.getPlanStartDate()));
        }
        insertObj.setStatus("0");
        QueryWrapper<PlanPriorityWork> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("priority_plan_code", insertObj.getPriorityPlanCode());

        if (planPriorityWorkMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planPriorityWorkMapper.insert(insertObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planPriorityWorkMapper.deleteBatchIds(idList);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanPriorityWorkReq planMining) {
        if (StrUtil.isBlank(planMining.getPriorityPlanId())){
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanPriorityWork updateObj = new PlanPriorityWork();
        copyProperties(planMining, updateObj, planMining.getPriorityPlanType(),"planStartDate","planEndDate");
        updateObj.setPriorityPlanName(generatePlanName(planMining.getPriorityPlanType(),updateObj.getPlanStartDate()));
        updateObj.setPriorityPlanCode(generatePlanCode(planMining.getPriorityPlanType(),updateObj.getPlanStartDate()));
        QueryWrapper<PlanPriorityWork> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("priority_plan_code", updateObj.getPriorityPlanCode());
        queryWrapper.ne("priority_plan_id", updateObj.getPriorityPlanId());
//        queryWrapper.eq("drivage_face_id", updateObj.getDrivageFaceId());
        if (planPriorityWorkMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planPriorityWorkMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }
    @Override
    public PlanPriorityWorkVo selectDetailById(String id) {
        PlanPriorityWork planDrivage = planPriorityWorkMapper.selectById(id);
        if (planDrivage == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planDrivage, PlanPriorityWorkVo.class);
    }

    @Override
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanPriorityWork planMining = planPriorityWorkMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planPriorityWorkMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }

            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }


    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanPriorityWork> buildQuery(PlanPriorityWorkReq req){
        LambdaQueryWrapper<PlanPriorityWork> lqw = new LambdaQueryWrapper<PlanPriorityWork>()
                .like(StrUtil.isNotBlank(req.getPriorityPlanCode()), PlanPriorityWork::getPriorityPlanCode, req.getPriorityPlanCode())
                .like(StrUtil.isNotBlank(req.getPriorityPlanName()), PlanPriorityWork::getPriorityPlanName, req.getPriorityPlanName())
                .eq(StrUtil.isNotBlank(req.getPriorityPlanType()), PlanPriorityWork::getPriorityPlanType, req.getPriorityPlanType())
                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanPriorityWork::getMineCode, req.getMineCode())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanPriorityWork::getStatus, req.getStatus())
                .and(o->o.eq(req.getMineCode()!=null, PlanPriorityWork::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanPriorityWork::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }
}
